package com.vehicle.admin.web.common.controller;

import com.vehicle.common.web.JsonResult;
import com.vehicle.common.web.editor.DateEditor;
import com.vehicle.common.web.editor.StringEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 控制器支持类
 * Created by yantingbin on 2017/7/18.
 */
public abstract class BaseController {
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        //String 类型转换,将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new StringEditor());
        binder.registerCustomEditor(Date.class, new DateEditor());
    }

    /**
     * 渲染失败数据
     * @return
     */
    protected JsonResult renderError(){
        JsonResult jsonResult=new JsonResult();
        jsonResult.setSuccess(false);
        jsonResult.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        return jsonResult;
    }

    /**
     * 渲染失败数据带消息
     * @param msg
     * @return
     */
    protected JsonResult renderError(String msg){
        JsonResult jsonResult=new JsonResult();
        jsonResult.setMsg(msg);
        jsonResult.setSuccess(false);
        jsonResult.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return jsonResult;
    }

    /**
     * 渲染成功的数据
     * @return
     */
    protected JsonResult renderSuccess(){
        JsonResult jsonResult=new JsonResult();
        jsonResult.setStatus(HttpServletResponse.SC_OK);
        jsonResult.setSuccess(true);

        return jsonResult;
    }

    /**
     * 渲染成功的数据（带消息）
     * @param msg
     * @return
     */
    protected JsonResult renderSuccess(String msg){
        JsonResult jsonResult=new JsonResult();
        jsonResult.setSuccess(true);
        jsonResult.setStatus(HttpServletResponse.SC_OK);
        jsonResult.setMsg(msg);

        return jsonResult;
    }

    /**
     * 渲染成功的数据（带数据）
     * @param obj
     * @param <T>
     * @return
     */
    protected <T> JsonResult<T> renderSuccess(T obj){
        JsonResult<T> jsonResult=new JsonResult();
        jsonResult.setSuccess(true);
        jsonResult.setStatus(HttpServletResponse.SC_OK);
        jsonResult.setResult(obj);

        return jsonResult;
    }

}
